package com.luci.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.Assert;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luci.common.exception.ApiCode;
import com.luci.common.supers.SuperServiceImpl;
import com.luci.common.tool.BeanTool;
import com.luci.sys.entity.Role;
import com.luci.sys.entity.User;
import com.luci.sys.entity.UserRole;
import com.luci.sys.entity.enums.UserStatusEnum;
import com.luci.sys.mapper.UserMapper;
import com.luci.sys.model.UserAddBo;
import com.luci.sys.model.UserEditBo;
import com.luci.sys.model.UserPageBo;
import com.luci.sys.service.IRoleService;
import com.luci.sys.service.IUserRoleService;
import com.luci.sys.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yuyanan
 * @since 2019-05-06
 */
@Service
public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Override
    public IPage<User> pageList(UserPageBo pageBo) {
        //构造条件
        QueryWrapper<User> queryWrapper = buildQueryWrapper(pageBo);
        //查询
        IPage<User> page = super.page(new Page<>(pageBo.getPage(), pageBo.getLimit()), queryWrapper);

        // 组装角色
        List<String> userIds = page.getRecords().stream().map(User::getId).collect(Collectors.toList());
        Map<String, Role> roleMap = iRoleService.getMapByUserIds(userIds);
        page.getRecords().forEach(user -> user.setRole(roleMap.get(user.getId())));
        return page;
    }

    private QueryWrapper<User> buildQueryWrapper(UserPageBo pageBo) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 条件
        if (StringUtils.isNotBlank(pageBo.getUsername())) {
            queryWrapper.like("username", pageBo.getUsername());
        }
        if (StringUtils.isNotBlank(pageBo.getRealname())) {
            queryWrapper.like("realname", pageBo.getRealname());
        }
        if (StringUtils.isNotBlank(pageBo.getMobile())) {
            queryWrapper.like("mobile", pageBo.getMobile());
        }
        // 排序
        if (StringUtils.isNotBlank(pageBo.getField())) {
            queryWrapper.orderBy(true, pageBo.isAsc(), pageBo.getField());
        } else {
            queryWrapper.orderBy(true, false, "create_time");
        }
        return queryWrapper;
    }

    @Override
    public void createUser(UserAddBo addBo) {
        Assert.notNull(ApiCode.ERROR, addBo, addBo.getUsername(), addBo.getRoleId());
        try {
            User user = new User();
            BeanUtils.copyProperties(addBo, user);
            user.setStatus(UserStatusEnum.OPEN);
            save(user);
            // 添加用户角色关系
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(addBo.getRoleId());
            iUserRoleService.save(userRole);
        } catch (DuplicateKeyException e) {
            Assert.fail("用户名已存在");
        }
    }

    @Override
    public User getUserContainRole(String id) {
        User user = getById(id);
        if (user != null) {
            Role role = iRoleService.getByUserId(id);
            user.setRole(role);
        }
        return user;
    }

    @Override
    public void editUser(UserEditBo editBo) {
        Assert.isNull(ApiCode.ERROR, editBo);
        Assert.isNull(ApiCode.ERROR, editBo.getId());
        Assert.isNull(ApiCode.ERROR, editBo.getRoleId());

        // 更新用户
        User old = getById(editBo.getId());
        if (old == null) {
            Assert.isNull(ApiCode.ERROR, old);
        }
        BeanTool.copyProperties(editBo, old);
        try {
            updateById(old);
        } catch (DuplicateKeyException e) {
            Assert.fail(ApiCode.USERNAME_EXIST);
            Assert.fail("用户名已存在");
        }

    }

    @Override
    public User login(String username, String password) {
        if (StringUtils.isAllBlank(username)) {
            Assert.fail("用户名不能为空");
        }
        if (StringUtils.isAllBlank(password)) {
            Assert.fail("用户名不能为空");
        }
        Wrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
        User sysUser = this.baseMapper.selectOne(wrapper);
        if (sysUser == null) {
            Assert.fail("帐号不存在");
        }
        if (!password.trim().equals(sysUser.getPassword().trim())) {
            Assert.fail("密码不正确");
        }
        return sysUser;
    }
}
